import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, NotificationOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'
import { getNotices, createNotice, getNotice, updateNotice, deleteNotice } from '../../../api/notice'

const { confirm } = Modal

const Notice = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentNotice, setCurrentNotice] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewNotice, setViewNotice] = useState(null)

    // 模拟数据
    const mockNotices = [
        {
            id: 1,
            title: '公司年度会议通知',
            content: '各部门负责人：\n\n公司将于2023年6月15日在大会议室举行年度会议，请各部门准备年度工作报告，并于会前一周提交。\n\n人事部',
            publisher: '张经理',
            department: '人事部',
            publishTime: '2023-06-01 09:00',
            expireTime: '2023-06-20 18:00',
            type: '会议通知',
            priority: '重要',
            status: '已发布',
            readCount: 25
        },
        {
            id: 2,
            title: '端午节放假安排',
            content: '全体员工：\n\n根据国家法定节假日安排，公司定于2023年6月22日至6月24日放假，共3天。6月25日（周日）正常上班。请各部门做好工作交接和安排。\n\n祝大家端午节快乐！\n\n人事部',
            publisher: '李经理',
            department: '人事部',
            publishTime: '2023-06-10 14:30',
            expireTime: '2023-06-25 18:00',
            type: '假期通知',
            priority: '普通',
            status: '已发布',
            readCount: 42
        },
        {
            id: 3,
            title: '系统维护通知',
            content: '全体员工：\n\n公司内部系统将于2023年6月18日（周日）进行升级维护，维护时间为上午9:00至下午15:00，期间系统将无法访问。请各位提前做好相关工作安排。\n\n技术部',
            publisher: '王工程师',
            department: '技术部',
            publishTime: '2023-06-15 11:00',
            expireTime: '2023-06-19 18:00',
            type: '系统通知',
            priority: '紧急',
            status: '草稿',
            readCount: 0
        }
    ]

    useEffect(() => {
        fetchNotices()
    }, [pagination.current, pagination.pageSize])

    // 获取通知数据
    const fetchNotices = async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize
            }
            const res = await getNotices(params)
            setDataSource(res.data.items || [])
            setPagination({
                ...pagination,
                total: res.data.total || 0
            })
        } catch (error) {
            message.error('获取公告列表失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = async (value) => {
        setLoading(true)
        try {
            const params = {
                page: 1,
                pageSize: pagination.pageSize,
                keyword: value
            }
            const res = await getNotices(params)
            setDataSource(res.data.items || [])
            setPagination({
                ...pagination,
                current: 1,
                total: res.data.total || 0
            })
        } catch (error) {
            message.error('搜索失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    // 添加通知
    const handleAdd = () => {
        setCurrentNotice(null)
        setVisible(true)
    }

    // 编辑通知
    const handleEdit = (record) => {
        setCurrentNotice(record)
        setVisible(true)
    }

    // 查看通知详情
    const handleView = async (id) => {
        try {
            const res = await getNotice(id)
            setViewNotice(res.data)
            setViewVisible(true)
        } catch (error) {
            message.error('获取公告详情失败')
            console.error(error)
        }
    }

    // 删除通知
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这条通知吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    await deleteNotice(id)
                    message.success('删除成功')
                    fetchNotices()
                } catch (error) {
                    message.error('删除失败')
                    console.error(error)
                }
            }
        })
    }

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            if (currentNotice) {
                // 编辑通知
                await updateNotice(currentNotice.id, values)
                message.success('编辑成功')
            } else {
                // 添加通知
                await createNotice(values)
                message.success('添加成功')
            }
            setVisible(false)
            fetchNotices()
        } catch (error) {
            message.error(currentNotice ? '编辑失败' : '添加失败')
            console.error(error)
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '发布人',
            dataIndex: 'publisher',
            key: 'publisher'
        },
        {
            title: '部门',
            dataIndex: 'department',
            key: 'department'
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type'
        },
        {
            title: '优先级',
            dataIndex: 'priority',
            key: 'priority',
            render: (text) => {
                let color = 'blue'
                if (text === '紧急') color = 'red'
                if (text === '重要') color = 'orange'
                if (text === '普通') color = 'blue'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                let color = text === '已发布' ? 'green' : 'volcano'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '发布时间',
            dataIndex: 'publishTime',
            key: 'publishTime'
        },
        {
            title: '阅读数',
            dataIndex: 'readCount',
            key: 'readCount'
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="notice-container">
            <Card title="通知管理" extra={
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加通知
                </Button>
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchNotices}
                    searchPlaceholder="搜索标题/发布人/部门/类型"
                />
            </Card>

            {/* 通知表单模态框 */}
            <Modal
                title={currentNotice ? '编辑通知' : '添加通知'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentNotice}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="title"
                        label="标题"
                        rules={[{ required: true, message: '请输入通知标题' }]}
                    >
                        <input placeholder="请输入通知标题" />
                    </Form.Item>
                    <Form.Item
                        name="content"
                        label="内容"
                        rules={[{ required: true, message: '请输入通知内容' }]}
                    >
                        <textarea placeholder="请输入通知内容" rows={6} />
                    </Form.Item>
                    <Form.Item
                        name="publisher"
                        label="发布人"
                        rules={[{ required: true, message: '请输入发布人' }]}
                    >
                        <input placeholder="请输入发布人" />
                    </Form.Item>
                    <Form.Item
                        name="department"
                        label="所属部门"
                        rules={[{ required: true, message: '请选择所属部门' }]}
                    >
                        <select>
                            <option value="人事部">人事部</option>
                            <option value="技术部">技术部</option>
                            <option value="市场部">市场部</option>
                            <option value="财务部">财务部</option>
                            <option value="管理部">管理部</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="type"
                        label="通知类型"
                        rules={[{ required: true, message: '请选择通知类型' }]}
                    >
                        <select>
                            <option value="会议通知">会议通知</option>
                            <option value="系统通知">系统通知</option>
                            <option value="假期通知">假期通知</option>
                            <option value="活动通知">活动通知</option>
                            <option value="其他通知">其他通知</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="priority"
                        label="优先级"
                        rules={[{ required: true, message: '请选择优先级' }]}
                    >
                        <select>
                            <option value="普通">普通</option>
                            <option value="重要">重要</option>
                            <option value="紧急">紧急</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value="草稿">草稿</option>
                            <option value="已发布">已发布</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="publishTime"
                        label="发布时间"
                        rules={[{ required: true, message: '请选择发布时间' }]}
                    >
                        <input type="datetime-local" />
                    </Form.Item>
                    <Form.Item
                        name="expireTime"
                        label="过期时间"
                        rules={[{ required: true, message: '请选择过期时间' }]}
                    >
                        <input type="datetime-local" />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 通知详情模态框 */}
            <Modal
                title="通知详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewNotice && (
                    <div className="notice-detail">
                        <Row gutter={[16, 16]}>
                            <Col span={24}>
                                <Tabs defaultActiveKey="1">
                                    <Tabs.TabPane tab="通知内容" key="1">
                                        <div style={{ padding: '16px' }}>
                                            <h2 style={{ textAlign: 'center', marginBottom: '16px' }}>{viewNotice.title}</h2>
                                            <div style={{ textAlign: 'center', color: '#888', marginBottom: '24px' }}>
                                                <span>发布人: {viewNotice.publisher}</span>
                                                <span style={{ margin: '0 16px' }}>|</span>
                                                <span>部门: {viewNotice.department}</span>
                                                <span style={{ margin: '0 16px' }}>|</span>
                                                <span>发布时间: {viewNotice.publishTime}</span>
                                            </div>
                                            <div style={{ whiteSpace: 'pre-line', lineHeight: '1.8' }}>
                                                {viewNotice.content}
                                            </div>
                                        </div>
                                    </Tabs.TabPane>
                                    <Tabs.TabPane tab="通知信息" key="2">
                                        <Descriptions bordered column={2}>
                                            <Descriptions.Item label="ID">{viewNotice.id}</Descriptions.Item>
                                            <Descriptions.Item label="标题">{viewNotice.title}</Descriptions.Item>
                                            <Descriptions.Item label="发布人">{viewNotice.publisher}</Descriptions.Item>
                                            <Descriptions.Item label="部门">{viewNotice.department}</Descriptions.Item>
                                            <Descriptions.Item label="通知类型">{viewNotice.type}</Descriptions.Item>
                                            <Descriptions.Item label="优先级">
                                                <Tag color={
                                                    viewNotice.priority === '紧急' ? 'red' : 
                                                    (viewNotice.priority === '重要' ? 'orange' : 'blue')
                                                }>
                                                    {viewNotice.priority}
                                                </Tag>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="状态">
                                                <Tag color={viewNotice.status === '已发布' ? 'green' : 'volcano'}>
                                                    {viewNotice.status}
                                                </Tag>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="阅读数">{viewNotice.readCount}</Descriptions.Item>
                                            <Descriptions.Item label="发布时间">{viewNotice.publishTime}</Descriptions.Item>
                                            <Descriptions.Item label="过期时间">{viewNotice.expireTime}</Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                </Tabs>
                            </Col>
                        </Row>
                    </div>
                )}
            </Modal>
        </div>
    )
}

export default Notice